#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>
#include <pthread.h>
#include <functional>
#include "InetAddr.hpp"
#include "Log.hpp"




const static int defaultsockfd = -1;
const static int backlog = 16;


enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR,
    USAGE_ERROR
};


class TcpServer;
class ThreadData
{
public:
    ThreadData(int fd,InetAddr addr,TcpServer* th):sockfd(fd)
    ,clientaddr(addr)
    ,self(th)
    {}
public:
    int sockfd;
    InetAddr clientaddr;
    TcpServer* self;
};

using func_t = std::function<std::string(const std::string& )>;

class TcpServer
{
public:
    TcpServer(const uint16_t port,func_t func) : _port(port),_func(func),_listensockfd(defaultsockfd), _isrunning(true)
    {
    }

    void InitServer()
    {
        _listensockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(FATAL, "sockfd create error");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "sockd cretae success, sockfd is: %d\n", _listensockfd);

        // 2.bind
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = bind(_listensockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "bind cretae success, sockfd is: %d\n", _listensockfd);

        // 3.tcp 是面向连接的，所以通信之前必须先建立链接，服务器是被连接的
        //  tcpserver 启动,未来首先要一直等待客户的链接到来

        n = ::listen(_listensockfd, backlog);
        if (n < 0)
        {
            LOG(FATAL, "listen error\n");
            exit(LISTEN_ERROR);
        }
        LOG(DEBUG, "listen sockd success, sockfd is: %d\n", _listensockfd);
    }
    void Service(int sockfd, InetAddr client)
    {
        LOG(DEBUG, "get a new line, info %s:%d, fd : %d\n", client.IP().c_str(), client.PORT(), sockfd);
        while (true)
        {
            std::string clientaddr = "[" + (std::string) "ip:" + client.IP() + "]" +
                                     "[" + (std::string) "port:" + std::to_string(client.PORT()) + "]" + "[" + "client say]# ";

            char inbuffer[1024];
            ssize_t n = recv(sockfd, inbuffer, sizeof(inbuffer) - 1,0);
            if (n > 0)
            {
                inbuffer[n] = 0;
                std::cout << clientaddr << inbuffer << std::endl;

                std::string result = _func(inbuffer);//回调函数执行完还要回来
                // 发回去
                // std::string echo_string = "[server echo]";
                // echo_string += inbuffer;
                write(sockfd, result.c_str(), result.size());
            }
            else if (n == 0)
            {
                LOG(INFO, "%s quit\n", client.IP().c_str());
                break;
            }
            else
            {
                LOG(INFO, "%s read error\n", client.IP().c_str());
                break;
            }
        }
        //::close(sockfd); // 文件描述符泄漏
    }

    static void* HandlerSock(void *args) //IO 和 业务解耦
    {
        pthread_detach(pthread_self());
        ThreadData* td = static_cast<ThreadData*>(args);
        td->self->Service(td->sockfd,td->clientaddr);

        delete td;
        return nullptr;
    }

    void Loop()
    {
        _isrunning = true;
        // 4.不能直接收数据，先获取链接
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = ::accept(_listensockfd, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error\n");
                continue;
            }
           
            // v2 多线程
            pthread_t t;
            ThreadData* td = new ThreadData(sockfd,InetAddr(peer),this);
            pthread_create(&t, nullptr, &HandlerSock, td);//将线程分离

        }
    }

    ~TcpServer()
    {
        if (_listensockfd > defaultsockfd)
        {
            ::close(_listensockfd);
        }
    }

private:
    uint16_t _port;
    int _listensockfd;
    bool _isrunning;

    func_t _func;
};